package com.clf.data.redis.core2;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;

import java.util.HashSet;
import java.util.Set;

@Configuration
@ConditionalOnClass({JedisCluster.class})
public class RedisConfiguration {

    @Autowired
    public RedisConfigerService redisConfigerService;

    @Bean
    public GenericObjectPoolConfig genericObjectPoolConfig() {
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxIdle(redisConfigerService.getMaxIdle());
        poolConfig.setMaxTotal(redisConfigerService.getMaxTotal());
        //poolConfig.setMinIdle(minidle);
        poolConfig.setMaxWaitMillis(redisConfigerService.getMaxWaitMillis());
        poolConfig.setTestOnBorrow(redisConfigerService.isTestOnBorrow());
        //poolConfig.setTestOnReturn(testOnReturn);
        poolConfig.setTestWhileIdle(redisConfigerService.isTestWhileIdle());
        return poolConfig;
    }


    @Bean
    public JedisCluster jedisCluster() {
        String[] cNodes = redisConfigerService.getNodes().split(",");
        Set<HostAndPort> nodes = new HashSet<>();
        //分割出集群节点
        for (String node : cNodes) {
            String[] hp = node.split(":");
            nodes.add(new HostAndPort(hp[0].trim(), Integer.parseInt(hp[1].trim())));
        }
        return new JedisCluster(nodes, redisConfigerService.getTimeout(), genericObjectPoolConfig());
    }



}
